package com.wkm.chainchain.state;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class ConsensusNodeBuildState {

    public static final int sleepTimeMills = 300;

    private static final String propFilePath = "BlockchainState/BlockchainState.properties";

    private static Properties prop = new Properties();

    private static final String clientStateKey = "ClientState";

    private static final String serverRunningNumKey = "ServerRunningNum";

    public static boolean getClientState() {
        prop = loadPropFromFile();
        boolean clientState = Boolean.parseBoolean(prop.getProperty(clientStateKey));
        return clientState;
    }

    public static void setClientState(boolean state) {
        prop = loadPropFromFile();
        prop.setProperty(clientStateKey, Boolean.toString(state));
        storePropToFile(prop);
    }

    public static int getServerRunningNum() {
        prop = loadPropFromFile();
        int runningNum = Integer.parseInt(prop.getProperty(serverRunningNumKey));
        return runningNum;
    }

    public static void addOneServerRunningNum() {
        prop = loadPropFromFile();
        int runningNum = Integer.parseInt(prop.getProperty(serverRunningNumKey));
        runningNum += 1;
        prop.setProperty(serverRunningNumKey, Integer.toString(runningNum));
        storePropToFile(prop);
    }

    public static void storePropToFile(Properties prop) {
        try (FileOutputStream out = new FileOutputStream(propFilePath)) {
            prop.store(out, null);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(propFilePath + " save failed!");
            System.exit(-1);
        }
    }

    public static Properties loadPropFromFile() {
        Properties prop = new Properties();
        try (FileInputStream in = new FileInputStream(propFilePath)) {
            prop.load(in);
        } catch (IOException e) {
            prop.setProperty(clientStateKey, Boolean.toString(false));
            prop.setProperty(serverRunningNumKey, new Integer("0").toString());
            storePropToFile(prop);
        }
        return prop;
    }

    public static void returnToZero() {
        Properties properties = new Properties();
        properties.setProperty(clientStateKey, Boolean.toString(false));
        properties.setProperty(serverRunningNumKey, new Integer("0").toString());
        storePropToFile(properties);
    }

}
